<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/31 0031
 * Time: 下午 8:26
 */
namespace app\dlc\common\helpers;
use app\common\model\ApiType;
use app\common\model\Article;
use app\common\model\CaseItem;
use think\Db;

class ApiHelper
{
//    获取分类
    static function getCategory($case_item_id){
        $caseItem = CaseItem::get($case_item_id);
        if ($caseItem['type']==2){
            $url = $caseItem->cases->website->admin_url;
            $url = substr($url,-1)=='/'?$url:$url.'/';
            $api = model('api_type')->where(['key'=>'category'])->find();
            if ($api){
                $url = $url . $api['url'];
                $param['api_name'] = $api['api_name'];
                $data = self::curl_post($url,$param);
                $data = json_decode($data,true);
                if ($data['code']==1){
                    return $data['data'];
                }
            }
        }
        return false;
    }
    //发送文章
    static function sendArticle($baseUrl,$ids){
            $url = $baseUrl;
            $url = substr($url,-1)=='/'?$url:$url.'/';
            //获取发布文章的api接口
            $api = model('api_type')->where(['key'=>'article_add'])->find();
            if ($api){
                $baidu_url = Db::name('website')->where(['admin_url' => $baseUrl])->value('baidu_url');
                $url = $url . $api['url'];
                $param['api_name'] = $api['api_name'];
                if (is_array($ids)){
                    $data = Db::name('article')->where(['id'=>['in',$ids]])->column('id,title,url as from_url,content,keywords,description,from,category_id');
                }

                if ($data){
                    foreach ($data as $key => $value) {
                        $article = Article::get($value['id']);
                        $data[$key]['base_url'] = $article['cases']['url'];
                        unset($data[$key]['id']);
                        $data[$key]['ctime'] = time();
                        //--------处理内容-------------
                        echo '---------------处理的文章id：' . $value['id'] . ',标题：' . $value['title'] . '-----------------------';
                        $data[$key]['content'] = self::filterConten($value['content'],$data[$key]['base_url'],$baseUrl);
                        dump($data[$key]['content']);
                    }
                    $param['data'] = json_encode($data);
                    $res = self::curl_post($url,$param);
                    $res = json_decode($res,true);
                    echo '返回的结果---------';
                    dump($res);
                    if ($res['code']){
                        $data = $res['data'];
                        self::tuisong($baidu_url,$data);
                        foreach ($data as $key => $value) {
                            $status = $value?3:-1;
                            Db::name('article')->where(['id'=>$key,'status'=>2])->update(['status'=>$status]);//已审核的文章才可以改变状态
                        }
                        return true;
                    }
                }else{
                    echo '无数据';
                }

            }else{
                echo '无接口';
            }
    }

    //推送到百度，通过接口的方式
    static function tuisong($baidu_url,$ids){
        $urls_pc = [];
        $site_url = end(explode( 'site=',$baidu_url));
        $site_url = explode('&token', $site_url)[0];
        foreach ($ids as $id) {
            if ($id>0){
                $api_url = $site_url . '/site/' . $id . '.html';
                $web_url = self::curl_get($api_url);
                $urls_pc[] = $web_url;
            }
        }
        if ($web_url&&count($urls_pc)>0){
            $ch = curl_init();
            $options =  array(
                CURLOPT_URL => $baidu_url,
                CURLOPT_POST => true,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POSTFIELDS => implode("\n", $urls_pc),
                CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
            );
            curl_setopt_array($ch, $options);
            $result = curl_exec($ch);

            echo '百度推送的结果-------';
            dump($urls_pc);
            dump($result);
            return true;
        }else{
            echo '无数据推送-------';
            return false;
        }


    }

    //处理conent的内容  $site_url  目标网站的url，解决部分图片用相对路径
    static function filterConten($str,$site_url,$api_base_url){
//        对于链接，没有添加网站前缀的，注定加上
        $str = str_replace('src="/','src="'.$site_url,$str);

        $imgs_url = HtmlHelper::getimgs($str)?:[];

        $arr = [];//组装成数组，避免重复的 去请求 图片接口
        foreach ($imgs_url as $url) {
//            1.判断链接是否能打开，如果不能，用$site_url 拼接下，如果还是不能打开的话，就用#代替,并不请求接口,判断失效了，注释掉
//            $open_url = '#';
//            if (HttpHelper::url_exists($url)){
//                $open_url = $url;
//            }elseif (HttpHelper::url_exists($site_url.$url)){
//                $open_url = $site_url.$url;
//            }

            $arr[$url] = $url;

        }
        dump($imgs_url);
        //            2.能打开图片，然后就请求图片接口，然后把接口返回的url，替换现在的url
        $api = ApiType::uploadPic($api_base_url);
        $param['api_name'] = $api['api_name'];
        foreach ($arr as $key=>$url) {
//            1.判断是否请求接口
            if ($url!="#"){
                $param['img_url'] = $url;
                $res = self::curl_post($api['url'],$param);
                $res = json_decode($res,true);
                if ($res['code']){
                    $url = $res['data'];
                }

            }

//            2.替换内容
            $str =  str_replace($key,$url,$str);
        }

//        dump($str);die;

        return $str;

    }

    static function curl_post($url,$param){
        $ch = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        // 配置
        curl_setopt($ch,CURLOPT_URL,$url);
        //增加配置，不让结果默认显示，并且可以接收
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);//0是默认值，默认把数据展示   1 不展示数据，可以接收   RETURN返回   TRANSFER转义、运输
        //添加配置，告诉curl我要用POST方式请求，因为curl发送请求的方式默认是get
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($param));//设置POST需要传递的值
        //执行
        $result = curl_exec($ch);
        $aStatus = curl_getinfo($ch);
        curl_close($ch);
        if (intval($aStatus["http_code"]) == 200) {
            return $result;
        } else {
            return false;
        }
    }

    static public function curl_get($url)
    {

        $info = curl_init();
        curl_setopt($info,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($info,CURLOPT_HEADER,0);
        curl_setopt($info,CURLOPT_NOBODY,0);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($info,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($info,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($info,CURLOPT_URL,$url);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }


}
